﻿#include "CVlcCtrMange.h"
#include "CLogOper.h"
#include "CHeader.h"
#include <qapplication.h>
#include <qmessagebox.h>
CVlcCtrMange::CVlcCtrMange(CBeltDataBase * pBeltData)
{
	m_pBeltData = pBeltData;
}

CVlcCtrMange::~CVlcCtrMange()
{
	/*if (m_pBeltData->m_nCamerState == 1)
	{
		stopRealPlay();
	}*/
}

bool CVlcCtrMange::ctrDevice(SCtrInfo & stCtrInfo)
{
	bool bOk = false;
	switch (stCtrInfo.m_enCtrCmd)
	{
	case enCPlay:
		bOk = realPlay(stCtrInfo);
		if (bOk)
		{
			SExecLog sLog;
			sLog.m_nAlarmLevel = 0;
			sLog.m_sDescriptionl = A2T("rtsp视频开启预览");
			sLog.m_sDevName = m_pBeltData->m_sBeltName;
			sLog.m_sFuncName = m_pBeltData->m_sName;
			if (sLog.m_sDescriptionl == "")
			{
				sLog.m_sDescriptionl = "/";
			}
			CLogOper::instance().addMsg(sLog);
			m_pBeltData->m_nCamerState = 0;
		}
		else
		{
			SExecLog sLog;
			sLog.m_nAlarmLevel = 0;
			sLog.m_sDescriptionl = A2T("rtsp视频开启失败");
			sLog.m_sDevName = m_pBeltData->m_sBeltName;
			sLog.m_sFuncName = m_pBeltData->m_sName;
			if (sLog.m_sDescriptionl == "")
			{
				sLog.m_sDescriptionl = "/";
			}
			CLogOper::instance().addMsg(sLog);
			m_pBeltData->m_nCamerState = 1;
		}
		break;
	case enCStopPlay:
		bOk = stopRealPlay(stCtrInfo);
		break;
	default:
		break;
	}
	return bOk;
}

bool CVlcCtrMange::realPlay(SCtrInfo & stCtrInfo)
{
	bool bOk = false;
	if (!m_mapVlcSdkOper.contains(stCtrInfo.m_hHwnd))
	{
		CVlcOper*pVlcSdkOper = new CVlcOper(m_pBeltData->m_sRtspUrl);
		QMetaObject::invokeMethod(QCoreApplication::instance(), [this,stCtrInfo ,&bOk, pVlcSdkOper]()
			{
				pVlcSdkOper->setImageWidget(stCtrInfo.m_pLabel);
				bOk = pVlcSdkOper->startCapture();  // 在主线程执行
			}, Qt::BlockingQueuedConnection); // ⚠️ 阻塞调用，等待执行完成
		if (bOk)
		{
			m_mapVlcSdkOper.insert(stCtrInfo.m_hHwnd, pVlcSdkOper);
		}
		else
		{
			delete pVlcSdkOper;
			pVlcSdkOper = NULL;
		}
		
	}
	else
	{
		bOk = true;
	}
	return bOk;
}

bool CVlcCtrMange::stopRealPlay(SCtrInfo & stCtrInfo)
{
	if (m_mapVlcSdkOper.contains(stCtrInfo.m_hHwnd))
	{
		bool bOk = false;
		CVlcOper* pVlcSdkOper = m_mapVlcSdkOper[stCtrInfo.m_hHwnd];
		QMetaObject::invokeMethod(QCoreApplication::instance(), [&bOk,pVlcSdkOper]()
			{
			   bOk = pVlcSdkOper->stopCapture();
			}, Qt::BlockingQueuedConnection); // ⚠️ 阻塞调用，等待执行完成
		if (bOk)
		{
			delete m_mapVlcSdkOper[stCtrInfo.m_hHwnd];
			m_mapVlcSdkOper[stCtrInfo.m_hHwnd] = nullptr;
			m_mapVlcSdkOper.remove(stCtrInfo.m_hHwnd);
		}
		else
		{
			m_mapVlcSdkOper.remove(stCtrInfo.m_hHwnd);
		}
		return true;
	}
	else
	{
		return true;
	}
}
